package com.jxb.lession76.web.servlet;

import com.jxb.lession76.common.Constant;
import com.sun.deploy.net.HttpResponse;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            String method = req.getParameter("method");
            Class aClass = this.getClass();
            Method method1 = aClass.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            String result = (String) method1.invoke(this, req, resp);
            if (result != null) {
                if (result.contains(Constant.Re.FORWARD)) {
                    req.getRequestDispatcher(result.replace(Constant.Re.FORWARD,"")).forward(req,resp);
                }else if (result.contains(Constant.Re.REDIRECT)) {
                    resp.sendRedirect(result.replace(Constant.Re.REDIRECT,""));
                }else {
                    resp.getWriter().println(result);
                }
            }
        } catch (Exception e) {
            resp.sendRedirect("/error.jsp");
        }

    }
}
